package com.pickgliss.utils
{
	import flash.display.DisplayObject;
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;

	public class DisplayPool
	{
		public function DisplayPool()
		{
			_objects = new Dictionary();
		}
		
		private static var _instance:DisplayPool;
		public static function get Instance():DisplayPool
		{
			if(_instance == null)
			{
				_instance = new DisplayPool();
			}
			return _instance;
		}
		
		private var _objects:Dictionary;
		public function clearAll():void
		{
			for (var key:String in _objects)
			{
				if(_objects[key])
				{
					while(_objects[key].length>0)
					{
						ObjectUtils.disposeObject(_objects[key].shift());
					}
				}
				delete _objects[key];
			}
		}
		
		public function creat(clazz:*):DisplayObject
		{
			var classname:String;
			if(clazz is String)classname = clazz;
			else classname = getQualifiedClassName(clazz);
			if(_objects[classname] == null)_objects[classname] = new Vector.<DisplayObject>();
			var objects:Vector.<DisplayObject> = _objects[classname];
			return getFreeObject(objects,classname);
		}
		
		private function getFreeObject(objects:Vector.<DisplayObject>,classname:String):DisplayObject
		{
			var len:int = objects.length;
			for(var i:int = 0;i<objects.length;i++)
			{
				if(objects[i].parent == null)return objects[i];
			}
			var objectClass:Class = getDefinitionByName(classname) as Class;
			var object:* = new objectClass();
			objects.push(object);
			return object;
		}
	}
}